<script lang="ts" setup>
import { cloneDeep } from 'lodash-es';
import type { Ref, UnwrapRef } from 'vue';
import { inject } from 'vue';
import { Modal, message } from 'ant-design-vue';
import type { AxiosResponse } from 'axios';
import axios from 'axios';
import { useColumn } from '../useColumn';
import useUserStore from '@/store/modules/user';

const props = defineProps({
  getDataByP: {
    type: Function as PropType<() => void>,
    required: true,
  },
  loading: {
    type: Boolean as PropType<boolean>,
    required: true,
  },
});
// 获取组织名称
const userStore = useUserStore();

const orgName = userStore.userOrgName;
// 数据处理
const data: Ref<any> = inject('data') as Ref<any>;
const total: Ref<any> = inject('total') as Ref<any>;
const keyWord: Ref<any> = inject('keyWord') as Ref<any>;
const { columns } = useColumn();

const editableData: UnwrapRef<Record<string, any>> = reactive({});

const selectedRowKeys: Ref<any> = inject('selectedId') as Ref<any>;

function onSelectionChange(newSelectedRowKeys: any[]) {
  selectedRowKeys.value = newSelectedRowKeys;
}

// 删除单条
async function deleteSingleRecord(id: number) {
  await deleteRecord<any, AxiosResponse<VAPI.DataResponse>>(id);
  const API_URL = 'http://172.26.7.151:8849//api/sxint-app-digital-comprehensive-platform/app1-engineer/Engineerdelete'; // 替换为您的API基础URL
  try {
    // 发送 DELETE 请求到后端服务
    const response = await axios.delete(`${API_URL}/data-items/${id}`);
    // 检查响应状态
    if (response.status === 200) {
      // 从 dataSource 中删除记录
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      message.success('记录删除成功');
    }
    else {
      // 处理非200响应状态
      const errorMessage = response.data?.msg || '未知错误';
      message.error(`删除失败：${errorMessage}`);
    }
  }
  catch (error: any) {
    // 处理错误情况
    let errorMessage = '删除时发生未知错误';
    if (error.response) {
      // 服务器端返回了错误响应
      errorMessage = error.response.data?.msg || '服务器返回错误';
      message.error(`删除失败：${errorMessage}`);
    }
    else if (error.request) {
      // 请求已发出但没有收到响应
      errorMessage = '请求已经发出，但没有收到响应';
    }
    else {
      // 发生了触发请求错误的问题
      errorMessage = error.message || '请求错误';
    }
    message.error(`删除时发生错误：${errorMessage}`);
  }
}

function edit(id: number) {
  editableData[id] = cloneDeep(data?.value?.filter((item: { id: number }) => id === item.id)[0]);
}

async function save(id: number) {
  const newData = Object.assign(data?.value?.filter((item: { id: number }) => id === item.id)[0], editableData[id]);
  if (newData.area !== orgName && orgName !== '') {
    message.error('不能修改分支局');
    return;
  }
  if (newData.account === '' && newData.invoice === '') {
    message.error('合同号或专票流水号必选其一');
    return;
  }
  if (newData.printflag !== '是' && newData.printflag !== '否') {
    message.error('是否已打印只能填 “是” 或 “否”');
    return;
  }
  const updateDate = {
    id: newData.id,
    area: newData.area,
    account: newData.account,
    printmonth: newData.printmonth,
    invoice: newData.invoice,
    amount: newData.amount,
    printflag: newData.printflag,
    operator: newData.operator,
    created: newData.created,
    billmonth: newData.billmonth,
  };
  await updateData(updateDate).then(() => {
    message.success('修改成功');
  });
  delete editableData[id];
}

function cancel(id: number) {
  delete editableData[id];
}

async function onDelete(id: number) {
  // const flag = ref<boolean>(false)
  Modal.confirm({
    title: () => '确定要删除吗？',
    okText: () => '是的',
    okType: 'danger',
    cancelText: () => '取消',
    onOk() {
      data.value = data.value.filter((item: { id: number }) => item.id !== id);
      deleteSingleRecord(id);
    },
  });
}

const pageSize: Ref<any> = inject('pageSize') as Ref<any>;
const current: Ref<any> = inject('current') as Ref<any>;
async function handleTableChange(pagination: any) {
  pageSize.value = pagination.pageSize;
  current.value = pagination.current;
  if (keyWord.value === '') {
    props.getDataByP();
  }
}
</script>

<template>
  <a-table
    :columns="columns" :data-source="data" row-key="id"
    :row-selection="{ selectedRowKeys, onChange: onSelectionChange }" :loading="props.loading"
    :pagination="{ pageSize, showQuickJumper: true, total }" :scroll="{ x: 1024 }" @change="handleTableChange"
  >
    <template #bodyCell="{ column, text, record }">
      <template
        v-if="['area', 'account', 'printmonth', 'billmonth', 'invoice', 'amount', 'printflag', 'operator', 'created'].includes(column.dataIndex as string)"
      >
        <div>
          <a-input
            v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex as string]"
            style="margin: -5px 0;"
          />
          <template v-else>
            {{ text }}
          </template>
        </div>
      </template>
      <template v-else-if="column.dataIndex === 'operation'">
        <div class="editable-row-operations">
          <span v-if="editableData[record.id]">
            <a-typography-link @click="save(record.id)">保存</a-typography-link>
            <a @click="cancel(record.id)">取消</a>
          </span>
          <span v-else>
            <a-space>
              <a @click="edit(record.id)">编辑</a>
              <a v-if="data.length" @click="onDelete(record.id)">删除</a>
            </a-space>
          </span>
        </div>
      </template>
    </template>
  </a-table>
</template>

<style lang="scss" scoped>
.v-table {
  flex-grow: 1;
  height: 100%;
  max-height: 100%;
  padding: 10px;
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
